<template>
  <div class="bluetooth-container">
    <h3 class="text-2xl font-bold mb-4">蓝牙设备连接</h3>

    <div class="mb-4">
      <button
          @click="connectDevice"
          class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
          :disabled="isScanning || isConnected"
      >
        {{ isScanning ? '正在扫描...' : isConnected ? '已连接' : '连接蓝牙设备' }}
      </button>

      <button
          @click="disconnectDevice"
          class="ml-4 px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 transition-colors"
          :disabled="!isConnected"
      >
        断开连接
      </button>
    </div>

    <div v-if="devices.length > 0" class="mb-4">
      <h4 class="text-lg font-semibold mb-2">可用设备:</h4>
      <ul class="space-y-2">
        <li
            v-for="device in devices"
            :key="device.id"
            class="p-2 border rounded hover:bg-gray-100 cursor-pointer"
            @click="selectDevice(device)"
        >
          {{ device.name || '未命名设备' }} ({{ device.id }})
        </li>
      </ul>
    </div>

    <div v-if="isConnected" class="mt-6">
      <h4 class="text-lg font-semibold mb-2">设备数据:</h4>
      <div class="p-4 bg-gray-50 rounded border">
        <pre>{{ deviceData }}</pre>
      </div>

      <div class="mt-4">
        <button
            @click="startReading"
            class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 transition-colors"
            :disabled="isReading"
        >
          {{ isReading ? '正在读取...' : '开始读取数据' }}
        </button>

        <button
            @click="stopReading"
            class="ml-4 px-4 py-2 bg-yellow-500 text-white rounded hover:bg-yellow-600 transition-colors"
            :disabled="!isReading"
        >
          停止读取
        </button>
      </div>
    </div>

    <div v-if="error" class="mt-4 p-4 bg-red-100 text-red-800 rounded border">
      <strong>错误:</strong> {{ error }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      devices: [],
      selectedDevice: null,
      server: null,
      characteristic: null,
      isScanning: false,
      isConnected: false,
      isReading: false,
      deviceData: '',
      error: null
    };
  },
  methods: {
    // 连接蓝牙设备
    async connectDevice() {
      this.error = null;
      this.devices = [];

      try {
        this.isScanning = true;

        // 扫描蓝牙设备
        const device = await navigator.bluetooth.requestDevice({
          filters: [{ services: ['00001101-0000-1000-8000-00805F9B34FB'] }], // 示例使用电池服务，实际使用时替换为你的设备服务UUID
          optionalServices: ['generic_access']
        });

        this.devices.push(device);
        this.selectedDevice = device;

        // 连接到设备
        await this.connectToSelectedDevice();

        this.isScanning = false;
      } catch (err) {
        this.isScanning = false;
        this.error = err.message;
        console.error('蓝牙连接错误:', err);
      }
    },

    // 连接到选定的设备
    async connectToSelectedDevice() {
      try {
        this.error = null;

        // 连接到设备GATT服务器
        const server = await this.selectedDevice.gatt.connect();
        this.server = server;

        // 获取服务
        const service = await server.getPrimaryService('battery_service'); // 替换为你的服务UUID

        // 获取特征值
        this.characteristic = await service.getCharacteristic('battery_level'); // 替换为你的特征值UUID

        this.isConnected = true;
        this.deviceData = '已成功连接到设备';
      } catch (err) {
        this.isConnected = false;
        this.error = err.message;
        console.error('连接到GATT服务器错误:', err);
      }
    },

    // 选择设备
    selectDevice(device) {
      this.selectedDevice = device;
      this.connectToSelectedDevice();
    },

    // 断开连接
    disconnectDevice() {
      if (this.selectedDevice && this.selectedDevice.gatt.connected) {
        this.selectedDevice.gatt.disconnect();
      }
      this.isConnected = false;
      this.isReading = false;
      this.deviceData = '';
    },

    // 开始读取数据
    async startReading() {
      if (!this.characteristic) return;

      try {
        this.isReading = true;
        this.deviceData = '开始读取数据...\n';

        // 监听特征值变化
        await this.characteristic.startNotifications();

        this.characteristic.addEventListener('characteristicvaluechanged', this.handleCharacteristicValueChanged);

        // 初始读取一次数据
        const value = await this.characteristic.readValue();
        this.handleCharacteristicValueChanged({ target: { value } });
      } catch (err) {
        this.isReading = false;
        this.error = err.message;
        console.error('读取数据错误:', err);
      }
    },

    // 停止读取数据
    async stopReading() {
      if (!this.characteristic) return;

      try {
        await this.characteristic.stopNotifications();
        this.characteristic.removeEventListener('characteristicvaluechanged', this.handleCharacteristicValueChanged);
        this.isReading = false;
        this.deviceData += '\n停止读取数据';
      } catch (err) {
        this.error = err.message;
        console.error('停止读取数据错误:', err);
      }
    },

    // 处理特征值变化
    handleCharacteristicValueChanged(event) {
      const value = event.target.value;
      const data = new Uint8Array(value.buffer);

      // 这里根据你的设备数据格式进行解析
      // 示例中我们假设数据是简单的数值
      const timestamp = new Date().toLocaleTimeString();
      this.deviceData += `[${timestamp}] 数据: ${Array.from(data)}\n`;
    }
  },
  beforeDestroy() {
    this.disconnectDevice();
  }
};
</script>

<style scoped>
.bluetooth-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

pre {
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 14px;
}
</style>
